package com.shixi.shixitraining.shixitraining.http;



import com.shixi.shixitraining.shixitraining.constant.Constants;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.shixi.shixitraining.shixitraining.constant.Constants.HOST;

/**
 *网络请求工具类
 */

public class HttpUtil {

    private static HttpUtil httpUtil;
    private APIInterface apiInterface;
    /**超时设置*/
    private  final int DEFAULT_TIMEOUT = 20;

    private String TAG = "HttpUtil";

    public HttpUtil(){


        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);


        if(!Constants.isDebug){
            builder.addInterceptor(logging);//过滤标记OkHttp
        }
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)    //连接超时秒
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);  //设置从服务器读取数据超时


        Retrofit retrofit =  new Retrofit.Builder()
                .baseUrl(HOST)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        apiInterface = retrofit.create(APIInterface.class);

    }

    public static synchronized HttpUtil getInstance(){
        if(httpUtil==null){
            httpUtil = new HttpUtil();
        }
        return httpUtil;
    }


    /**
     * 默认的前缀网址为BASE_URL
     * @return
     */
    public APIInterface getApiInterface(){
        return apiInterface;
    }


}
